package com.jmb.apiplatform.common;


import com.jmb.apiplatform.exception.ValidException;
import com.jmb.apiplatform.util.RedisUtil;
import com.jmb.apiplatform.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
@Slf4j
public class LoginUserInfo {



    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private TokenUtil tokenUtil;


    public Object getUserToken(HttpServletRequest request) throws ValidException {

        String token = request.getHeader("Token");
        String userId = request.getHeader("UserId");
        if (token==null){
             throw new ValidException("用户未登录");
         }
        return redisUtil.get("login:"+userId);
    }

    // 获取用户的真实姓名
    public String getRealName(HttpServletRequest request) throws ValidException {
        HashMap<String,Object> userToken = (HashMap<String, Object>) getUserToken(request);
        Object username = userToken.get("username");
        if (username==null){
            throw new ValidException("获取到到的username为空");
        }

        return username.toString();
    }
    // 获取用户的id
    public Integer getUserId(HttpServletRequest request) throws ValidException {
        HashMap<String,Object> userToken = (HashMap<String, Object>) getUserToken(request);
        Object userId = userToken.get("userId");
        if (userId==null){
            throw new ValidException("获取到到的userId为空");
        }
        return userId.hashCode();
    }

}
